package com.echoesnet.echoesshortvideo.Activities;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.StepRegisterViewModel;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;

public class NewBindCodeAct extends BaseActivity implements View.OnClickListener
{
    @BindView(R.id.phone)
    TextView phone;

    @BindView(R.id.phone_code)
     EditText editText;
    @BindView(R.id.nextOk)
    ImageView ivNext;
    @BindView(R.id.scrollLayout)
    RelativeLayout rl;

    private StepRegisterViewModel lModel;

    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    @BindView(R.id.root_layout)
    View activityRootView;
    @BindView(R.id.reSendTime)
    TextView reSendTime;
    @BindView(R.id.tvVerifyTime)
    TextView tvVerifyTime;

    @BindView(R.id.reSend)
    TextView reSend;
    @BindView(R.id.tvVerify)
    TextView tvVerify;
    private String sPhone;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_new_bind_code);

        ButterKnife.bind(this);
        sPhone=getIntent().getStringExtra("phone");
        editText.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                if(s.length()<6)
                {
                    ivNext.setClickable(false);
                    ivNext.setAlpha(0.5f);
                }
                else
                {
                    ivNext.setClickable(true);
                    ivNext.setAlpha(1f);
                }
            }

            @Override
            public void afterTextChanged(Editable s)
            {

            }
        });


        lModel=new StepRegisterViewModel();
        lModel.getLiveData().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String type)
            {
                if (type==null)
                    return;

                if(type.equals("checkCodeOk"))
                {
                    lModel.bindPhone(sPhone,"");
                }
                else if(type.equals("bindPhoneOk"))
                {
                    ToastUtils.showShort("更改绑定成功");
                    Intent intent=new Intent(NewBindCodeAct.this,MySettingActivity.class);
                    intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP|FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    finish();
                }
                else
                editText.setText(type);
            }
        });

        lModel.sendVerificationCode(getIntent().getStringExtra("phone"),"4");
        reSend.setEnabled(false);
        reSend.setTextColor(ContextCompat.getColor(this, R.color.v2));
        tvVerify.setEnabled(false);
        tvVerify.setTextColor(ContextCompat.getColor(this, R.color.v2));
        reSendTime.setVisibility(View.VISIBLE);
        ttMsgCountDown = new SecurityCountDown();
        MsgTimer.scheduleAtFixedRate(ttMsgCountDown, 0, 1000);
        //获取屏幕高度
        screenHeight = CommonUtils.getScreenHeight(this);
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;
        //添加layout大小发生改变监听器
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
    }

    @OnClick({R.id.cancle,R.id.reSend,R.id.tvVerify,R.id.nextOk})
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.cancle:
                finish();
                break;
            case R.id.nextOk:
                lModel.checkVerifyCode(sPhone,
                        editText.getText().toString().trim(),"4");
                break;
            case R.id.reSend:
                //重新发送
                lModel.sendVerificationCode(phone.getText().toString().replace("+86","").trim(),"4");

                reSend.setEnabled(false);
                reSend.setTextColor(ContextCompat.getColor(this, R.color.v2));
                tvVerify.setEnabled(false);
                tvVerify.setTextColor(ContextCompat.getColor(this, R.color.v2));

                reSendTime.setVisibility(View.VISIBLE);
                ttMsgCountDown = new SecurityCountDown();
                MsgTimer.scheduleAtFixedRate(ttMsgCountDown, 0, 1000);
                break;
            case R.id.tvVerify:
                //语音验证
                lModel.sendVoiceCode(phone.getText().toString().replace("+86","").trim(),"4");

                tvVerify.setEnabled(false);
                tvVerify.setTextColor(ContextCompat.getColor(this, R.color.v2));
                reSend.setEnabled(false);
                reSend.setTextColor(ContextCompat.getColor(this, R.color.v2));

                tvVerifyTime.setVisibility(View.VISIBLE);
                ttAudioMsgCountDown = new SoundCodeCountDown();
                AudioTimer.scheduleAtFixedRate(ttAudioMsgCountDown, 0, 1000);
                break;
        }

    }

    private void updateViewHeight(boolean flag)
    {
        RelativeLayout.LayoutParams pa= (RelativeLayout.LayoutParams) rl.getLayoutParams();
        pa.topMargin=flag?LoginAct.TOP_MARGIN:0;
        rl.setLayoutParams(pa);
    }

    ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener()
    {

        @Override
        public void onGlobalLayout()
        {
            activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);

            Rect r = new Rect();
            activityRootView.getWindowVisibleDisplayFrame(r);

            //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
            if (screenHeight-r.bottom  > keyHeight)
            {
                updateViewHeight(true);
            } else
            {
                updateViewHeight(false);
            }
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
        }
    };


    private TimerTask ttMsgCountDown;
    private TimerTask ttAudioMsgCountDown;
    private Timer MsgTimer=new Timer();
    private Timer AudioTimer=new Timer();
    private int msgCountdown=60;
    private  int  audioCountdown=60;

    /**
     * 验证码倒计时
     */
    private class SecurityCountDown extends TimerTask
    {
        @Override
        public void run()
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    reSendTime.setText(String.format("%ss", String.valueOf(msgCountdown--)));
                    if (msgCountdown < 1)
                    {
                        resetGetSecurityButton();
                    }
                }
            });
        }
    }

    /**
     * 重置验证码获取按钮
     */
    private void resetGetSecurityButton()
    {
        tvVerify.setEnabled(true);
        tvVerify.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        reSend.setEnabled(true);
        reSend.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        reSendTime.setVisibility(View.GONE);
        msgCountdown = 60;
        if (ttMsgCountDown != null)
            ttMsgCountDown.cancel();

    }


    /**
     * 语音验证码倒计时
     */
    private class SoundCodeCountDown extends TimerTask
    {
        @Override
        public void run()
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    tvVerifyTime.setText(String.format("%ss", String.valueOf(audioCountdown--)));
                    if (audioCountdown < 1)
                    {
                        resetGetSoundCodeButton();
                    }
                }
            });
        }
    }

    /**
     * 重置验证码获取按钮
     */
    private void resetGetSoundCodeButton()
    {
        tvVerify.setEnabled(true);
        tvVerify.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        reSend.setEnabled(true);
        reSend.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        tvVerifyTime.setVisibility(View.GONE);
        audioCountdown = 60;
        if (ttAudioMsgCountDown != null)
            ttAudioMsgCountDown.cancel();
    }


}
